package com.jy.appmarket.activity;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardListView;
import it.gmariotti.cardslib.library.view.PullToRefreshListView.RefreshingListener;

import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.Toast;

import com.jy.appmarket.R;
import com.jy.appmarket.cards.BaseUICard;
import com.jy.appmarket.cards.CardsUtils;
import com.jy.appmarket.cards.DownloadableUICard;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.model.CategoryInfo;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.CardPageNetEngine;
import com.jy.appmarket.network.engine.cachestrategy.CacheStrategy;
import com.jy.appmarket.network.resultdata.PageResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.view.LoadingView;
import com.jy.appmarket.view.flowlayout.FlowLayout;
import com.umeng.analytics.MobclickAgent;

public class CategoryActivity extends DownloadActivity implements NetTaskListener,
		LoadingView.OnClickListener, RefreshingListener {
	private static final String TAG = CategoryActivity.class.getSimpleName();
	public static final String EXTRA_CATE_NAME = "category_name";
	public static final String EXTRA_CATE_PATH = "category_path";
	public static final String EXTRA_SUBS = "category_subs";
	public static final String EXTRA_SUB_INDEX = "category_sub_index";
	public static final String EXTRA_SOURCE = "category_source";

	private CardListView mListview;
	private CardArrayAdapter mCardsAdapter;
	private ArrayList<Card> mCardsArray = new ArrayList<Card>();
	private NetTask mNetTask;

	private LoadingView mLoadingView;
	private FlowLayout mFlowLayout;
	private int mPageIndex = 1;
	private boolean mIsFooterRefresh = false;
	private long mDataVersion;
	private String mPath;
	// private String mSource;
	private String mCateName;
	private String mCatePath;
	private ArrayList<CategoryInfo> mSubs;
	private int mSubIndex;
	private boolean mIsConnecting = false;
	private boolean mReloading = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_category);
		getExtras();
		initTitle();
		initLoadingView();
		initListView();
		updateSubs();
		loadData(true);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle(mCateName);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
		mFlowLayout = findViewById(R.id.category_layout_flowlayout);
		if (mSubs == null || mSubs.isEmpty()) {
			mFlowLayout.setVisibility(View.GONE);
			findViewById(R.id.category_divider).setVisibility(View.GONE);
		} else {
			mFlowLayout.setVisibility(View.VISIBLE);
			findViewById(R.id.category_divider).setVisibility(View.VISIBLE);
			LayoutInflater li = LayoutInflater.from(this);

			for (int i = 0; i < mSubs.size(); i++) {
				View v = li.inflate(R.layout.category_item, mFlowLayout, false);
				RadioButton rb = v.findViewById(R.id.category_item_title);
				rb.setText(mSubs.get(i).getName());
				final int index = i;
				v.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if (!mIsConnecting) {
							mSubIndex = index;
							mReloading = true;
							mPath = mSubs.get(index).getUrl();
							mCardsArray.clear();
							mListview.setAdapter(mCardsAdapter);
							updateSubs();
							loadData(true);
							clearFileListener();
						}
					}
				});
				mFlowLayout.addView(v);
			}

		}
	}

	private void getExtras() {
		if (getIntent() == null) {
			return;
		}
		Bundle extras = getIntent().getExtras();
		if (extras == null) {
			return;
		}
		mCateName = extras.getString(EXTRA_CATE_NAME);
		mCatePath = extras.getString(EXTRA_CATE_PATH);
		mSubs = extras.getParcelableArrayList(EXTRA_SUBS);
		mSubIndex = extras.getInt(EXTRA_SUB_INDEX, 0);
		// mSource = extras.getString(EXTRA_SOURCE);
		if (mSubs == null) {
			mSubs = new ArrayList<CategoryInfo>();
		}
		CategoryInfo all = new CategoryInfo();
		all.setName(getString(R.string.all));
		all.setUrl(mCatePath);
		mSubs.add(0, all);
		if (mSubIndex == -1) {
			mSubIndex = 0;
		} else if (mSubIndex >= 0 && mSubIndex < mSubs.size() - 1) {
			mSubIndex++;
		} else {
			mSubIndex = 0;
		}
		mPath = mSubs.get(mSubIndex).getUrl();
	}

	private void updateSubs() {
		for (int i = 0; i < mFlowLayout.getChildCount(); i++) {
			RadioButton rb = mFlowLayout.getChildAt(i).findViewById(
					R.id.category_item_title);
			rb.setChecked(mSubIndex == i);
		}
	}

	private void subsEnable(boolean isEnable) {
		for (int i = 0; i < mFlowLayout.getChildCount(); i++) {
			RadioButton rb = mFlowLayout.getChildAt(i).findViewById(
					R.id.category_item_title);
			// rb.setChecked(mSubIndex == i);
			rb.setEnabled(isEnable);
		}
	}

	private void loadData(boolean loadFirstPage) {
		subsEnable(false);
		mIsConnecting = true;
		int pageIndex = mPageIndex;
		if (loadFirstPage) {
			pageIndex = 1;
			mDataVersion = 0;
			mListview.setVisibility(View.GONE);
			mListview.needToRefreshOnFooter(true);
			mListview.needToRefreshOnHeader(false);
			mLoadingView.showWaitView(R.string.ptr1_loading_wait);
		}
		CardPageNetEngine engine = new CardPageNetEngine(mPath, mDataVersion, pageIndex);
		engine.setCacheStrategy(new CacheStrategy(true, CacheStrategy.THREE_HOUR));
		mNetTask = new NetTask(this, engine, 1);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	private void initListView() {
		mListview = findViewById(R.id.discovery_fragment_cardlist);
		mListview.setEmptyView(mLoadingView);
		mListview.needToRefreshOnFooter(true);
		mListview.needToRefreshOnHeader(false);
		mListview.setRefreshListener(this);
		mListview.setVisibility(View.GONE);

		mCardsAdapter = new CardArrayAdapter(this, mCardsArray);
		mCardsAdapter.setInnerViewTypeCount(100);
		mListview.setAdapter(mCardsAdapter);
	}

	private void initLoadingView() {
		mLoadingView = findViewById(R.id.loading_view_layout);
		mLoadingView.setOnClickListener(this);
		mLoadingView.showWaitView(getString(R.string.loading_wait));
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		subsEnable(true);
		updateSubs();
		mIsConnecting = false;
		mReloading = false;
		PageResult resultData = (PageResult) engine.getResultData();
		if (!resultData.isOK()) {
			if (mPageIndex == 1) {
				mLoadingView.showErrorView(R.string.load_failed_retry);
			}
		} else {
			List<com.jy.app.market.idata.card.Card> cards = resultData.getCards();
			if (cards == null || cards.size() == 0) {
				if (mLoadingView.getVisibility() == View.VISIBLE) {
					// LogUtil.d(TAG, "pageNo:" + mPageIndex + " ");
					mLoadingView.showErrorView(R.string.no_data);
					return;
				}
			} else {
				mPageIndex = resultData.getPageNo();
				mDataVersion = resultData.getDataVersion();
				for (com.jy.app.market.idata.card.Card card : cards) {
					BaseUICard uiCard = CardsUtils.getCardInstance(this, card);
					if (uiCard == null) {
						LogUtil.w(TAG, "Unsupport card:" + card.getType());
						continue;
					}

					uiCard.setIndex(mCardsArray.size());

					if (uiCard instanceof DownloadableUICard) {
						DownloadableUICard c = (DownloadableUICard) uiCard;
						c.setListView(mListview);
						addFileListener(c);
					}

					uiCard.setApkSource(new ApkSource(mPath, uiCard.getIndex(), mDataVersion));
					mCardsArray.add(uiCard);
				}
				mCardsAdapter.notifyDataSetChanged();
				mListview.footerRefreshingCompleted();
				mListview.setVisibility(View.VISIBLE);
				mLoadingView.setVisibility(View.GONE);
				mPageIndex++;
				if (mIsFooterRefresh) {
					mIsFooterRefresh = false;
				}

				if (resultData.getPageNo() >= resultData.getTotalPage()) {
					mListview.needToRefreshOnFooter(false);
				}
			}
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		subsEnable(true);
		mIsConnecting = false;
		mReloading = false;
		if (mCardsAdapter.isEmpty()) {
			mListview.setVisibility(View.GONE);
			mLoadingView.showErrorView(getString(R.string.ptrl_refresh_fail));
		} else {
			if (mIsFooterRefresh) {
				mListview.footerRefreshError();
				mIsFooterRefresh = false;
			}
		}
		Toast.makeText(this, R.string.network_error, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onTaskRunCanceled(int tag) {
		subsEnable(true);
		mIsConnecting = false;
		mReloading = false;
	}

	@Override
	public void onLoadingViewClick(View view) {
		loadData(true);
	}

	@Override
	public void onHeaderRefreshing() {
		// nothing todo
	}

	@Override
	public void onFooterRefreshing() {
		mIsFooterRefresh = true;
		if (!mReloading) {
			loadData(false);
		}
	}
}